package doning;

import org.junit.Test;

import java.util.*;

import static com.study.util.LogUtil.info;

/**
 * 295. Find Median from Data Stream 数据流的中位数
 * <p>
 * 中位数是有序列表中间的数。如果列表长度是偶数，中位数则是中间两个数的平均值。
 * 例如，
 * [2, 3, 4] 的中位数是 3
 * [2, 3] 的中位数是 (2 + 3) / 2 = 2.5
 * 设计一个支持以下两种操作的数据结构：
 * void addNum(int num) - 从数据流中添加一个整数到数据结构中。
 * double findMedian() - 返回目前所有元素的中位数。
 * <p>
 * 2019-05-19 10:01
 **/
@SuppressWarnings("all")
public class FindMedianFromDataStream {

    class MedianFinder {

        List<Integer> list;

        public MedianFinder() {
            // TODO
            list = new ArrayList();
        }

        public void addNum(int num) {
            // TODO
            int left = 0;
            int right = list.size() - 1;
            while (left < right) {
                int mid = left + (right - left) / 2;
                int val = list.get(mid);
                if (val < num)
                    left = mid + 1;
                else
                    right = mid;
            }
            if (list.size() > 0 && num > list.get(list.size() - 1))
                list.add(num);
            else
                list.add(left, num);
        }

        public double findMedian() {
            // TODO
            int len = list.size();
            if (len % 2 == 1)
                return (double) list.get(len / 2);
            else
                return list.get(len / 2) / 2.0
                        + list.get(len / 2 - 1) / 2.0;
        }
    }

    @Test
    public void test() {
        MedianFinder mf = new MedianFinder();
        mf.addNum(1);
        mf.addNum(2);
        info(mf.findMedian());// -> 1.5
        mf.addNum(3);
        info(mf.findMedian());// -> 2
    }
}



























/*
List<Integer> list;

public MedianFinder() {
    list = new ArrayList();
}

public void addNum(int num) {
    int left = 0;
    int right = list.size() - 1;
    while (left < right) {
        int mid = left + (right - left) / 2;
        int val = list.get(mid);
        if (val < num)
            left = mid + 1;
        else
            right = mid;
    }

    if (list.size() > 0 && num > list.get(list.size() - 1))
        list.add(num);
    else
        list.add(left, num);
}

public double findMedian() {
    int len = list.size();
    if (len % 2 == 1)
        return (double) list.get(len / 2);
    else
        return list.get(len / 2) / 2.0
                + list.get(len / 2 - 1) / 2.0;
}
*/
